package com.pig4cloud.pigx.system.runner;

import com.pig4cloud.pigx.common.customize.redis.constants.CommonRedisConstants;
import com.pig4cloud.pigx.system.constant.RedisHashKeyConstant;
import com.pig4cloud.pigx.system.service.SystemPlatformService;
import com.pig4cloud.pigx.system.service.SystemProductService;
import com.pig4cloud.pigx.system.service.SystemSymbolService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 */
@Component
@Slf4j
@AllArgsConstructor
public class InitRedisRunner implements ApplicationRunner {

    private final SystemSymbolService symbolService;

    private final SystemProductService systemProductService;

    private final SystemPlatformService systemPlatformService;
    private final RedisTemplate redis;

    @Override
    public void run(ApplicationArguments args) {
        initSymbolList();
        initProduct();
        initPlatform();
    }

    /**
     * 初始化币对redis
     */
    private void initSymbolList() {
        try {
            symbolService.updateRedis();
            Set<String> keys = redis.opsForHash().keys(RedisHashKeyConstant.SYMBOL_LIST);
            for (String key : keys) {
                if (redis.opsForValue().get(CommonRedisConstants.OKX + CommonRedisConstants.OPEN_PRICE + key) == null) {
                    Object lastPrice = redis.opsForValue().get(CommonRedisConstants.OKX + CommonRedisConstants.LAST_PRICE + key);
                    if (key.equals("UNTUSDT")) {
                        lastPrice = redis.opsForValue().get(CommonRedisConstants.OKX + CommonRedisConstants.LAST_PRICE + "UNT");
                    }
                    if (lastPrice != null) {
                        redis.opsForValue().set(CommonRedisConstants.OKX + CommonRedisConstants.OPEN_PRICE + key, lastPrice);
                    }
                }
            }

            System.err.println("币对信息 redis 初始化完成");
        } catch (Exception e) {
            log.error("币对信息 redis 初始化失败");
        }

    }

    /**
     * 初始化产品redis
     */
    private void initProduct() {
        try {
            systemProductService.initRedis();
            System.err.println("产品信息 redis 初始化完成");
        } catch (Exception e) {
            log.error("产品信息 redis 初始化失败");
        }
    }

    /**
     * 初始化平台redis
     */
    private void initPlatform() {
        try {
            systemPlatformService.initRedis();
            System.err.println("平台信息 redis 初始化完成");
        } catch (Exception e) {
            log.error("平台信息 redis 初始化失败");
        }
    }

}
